package com.atomikos1.config;

import com.atomikos1.config.dataproperties.DataSource1Properties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/24  13:46
 * 描述:
 */
@Configuration
@MapperScan(basePackages = {"com.atomikos1.mapper.dao1"},sqlSessionFactoryRef="sqlSessionFactory1")
public class DataSource1Config {


    @Bean("dataSource1")
    @Primary
    public DataSource getDataSource1(DataSource1Properties dataSource1Properties){

        Properties xaProperties=new Properties();
        xaProperties.put("url",dataSource1Properties.getUrl());
        xaProperties.put("username",dataSource1Properties.getUsername());
        xaProperties.put("password",dataSource1Properties.getPassword());

        AtomikosDataSourceBean atomikosDataSourceBean=new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSourceClassName("com.alibaba.druid.pool.xa.DruidXADataSource");
        atomikosDataSourceBean.setUniqueResourceName("manger2");
        atomikosDataSourceBean.setPoolSize(5);
        atomikosDataSourceBean.setXaProperties(xaProperties);

        return atomikosDataSourceBean;
    }


    @Primary
    @Bean("sqlSessionFactory1")
   public SqlSessionFactory getSqlSessionFactory(@Qualifier("dataSource1") DataSource dataSource) throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:/mapper/db1/*.xml"));

        return sqlSessionFactoryBean.getObject();

   }

}
